package dp;

/**
 * 连续子数组最大和，动态规划问题
 * R[i]表示以i号元素结尾的子数组最大和，易知递推公式为：
 * 1）R[i]=A[i]; 若i=0
 * 2）R[i]=R[i-1]+A[i];若R[i-1]>=0;
 * 3）R[i]=A[i]; 若R[i-1]<0;
 *
 * @author zj
 */
public class ContinuousSubArrayMaxSum {

    public static void main(String args[]) {
        int A[] = {1, -2, 3, 10, -4, 7, 2, -5};
        //int A[] = {-9,-2,-3,-5,-3};
        //int A[] ={0,-2,3,5,-1,2};
        System.out.println(solution(A));
    }

    public static int solution(int arr[]) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        int tmp[] = new int[arr.length];
        tmp[0] = arr[0];  //边界条件
        int max = tmp[0];
        for (int i = 1; i < arr.length; i++) {
            if (tmp[i - 1] < 0) {
                tmp[i] = arr[i];
            } else {
                tmp[i] = tmp[i - 1] + arr[i];
            }
            max = tmp[i] > max ? tmp[i] : max;
        }
        for (int i = 0; i < tmp.length; i++) {
            System.out.print(tmp[i] + " ");
        }
        System.out.println();
        return max;
    }
}
